import java.util.*;

public class demo1 {
    //连接表
    HashMap<Character, HashSet<Character>> map = new HashMap<>();
    HashMap<Character, Integer> in = new HashMap<>();//记录该点的入度
    boolean flag = false;

    public String alienOrder(String[] words) {

        //初始化哈希in
        for (String s : words) {
            for (int i = 0; i < s.length(); i++) {
                in.put(s.charAt(i), 0);
            }
        }
        //创建连接表
        for (int i = 0; i < words.length; i++) {
            for (int j = i + 1; j < words.length; j++) {
                add(words[i], words[j]);
                if(flag)return "";
            }
        }
        Queue<Character>queue=new LinkedList<>();
        for (Map.Entry<Character,Integer>entry:in.entrySet()) {
            if(entry.getValue()==0)queue.add(entry.getKey());
        }
        StringBuilder builder=new StringBuilder();
        while (!queue.isEmpty()){
            Character poll = queue.poll();
            builder.append(poll);
            HashSet<Character> mapOrDefault = map.getOrDefault(poll, new HashSet<Character>());
            for(Character c:mapOrDefault){
                if(in.containsKey(c)){
                    in.put(c,in.get(c)-1);
                    if(in.get(c)==0){
                        queue.add(c);
                    }
                }
            }
        }
        for (String s : words) {
            for (int i = 0; i < s.length(); i++) {
                if(in.get(s.charAt(i))!=0)return "";
            }
        }
        return builder.toString();
    }

    public void add(String s1, String s2){
        int n=Math.min(s1.length(),s2.length());
        int i=0;
        for (; i <n ; i++) {
            char x=s1.charAt(i);
            char y=s2.charAt(i);
            if(x!=y){
                //x->y
                if(!map.containsKey(x)){
                    map.put(x,new HashSet<>());
                }
                if(!map.get(x).contains(y)){
                    map.get(x).add(y);
                    in.put(y, in.getOrDefault(y,0)+1);
                }
                break;
            }
        }
        //防止当s1.equals(s2)正确时flag不改变   符合条件
        if(i==s2.length()&&i<s1.length())flag=true;
    }
}
